<template>
  <div v-if="isShow" style="width: 720px;height: 606px;position: relative;">
    <div style="width: 720px;height: 500px;">
      <div style="display:flex;margin-left: 330px;  text-align: center;">
        <h2>{{ user.uName }}</h2>
      </div>
      <div class="overflow" id="overflow" style="width: 720px;height: 470px; overflow-x: hidden;overflow-y: auto;">
        <div v-for="(item,index) in messageList" :key="index">
          <div
            v-if="item.userID !== myUser[0].uid && (item.messageIMG === null || item.messageIMG ==='') && (item.messageSVG === null || item.messageSVG === '') && (item.message !== null)"
            style="width: 100%;height: auto;display: flex;margin-top: 10px;margin-bottom: 10px;">
            <img :src="user.uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
            <div
              style="min-width: 60px;max-width: 350px; width: auto;height: auto;padding: 5px;margin-left: 2px; background-color: #fff;border-radius: 10px;">
              {{ item.message }}
            </div>
          </div>
          <div
            v-if="item.userID === myUser[0].uid && (item.messageIMG === null || item.messageIMG ==='') && (item.messageSVG === null || item.messageSVG === '') && (item.message !== null)"
            style="width: 100%;height: auto;display: flex;flex-direction: row-reverse;margin-top: 10px;margin-bottom: 10px;">
            <img :src="myUser[0].uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
            <div
              style="min-width: 60px;max-width: 350px;width: auto;height: auto;padding: 5px; background-color: chartreuse;border-radius: 10px;">
              {{ item.message }}
            </div>
          </div>
          <div
            v-if="item.userID === myUser[0].uid && (item.messageIMG !== null && item.messageIMG!=='') && (item.messageSVG === null || item.messageSVG === '') && (item.message === null || item.message ==='') "
            style="width: 100%;height: auto;display: flex;flex-direction: row-reverse;margin-top: 10px;margin-bottom: 10px;">
            <img :src="myUser[0].uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
            <div
              style="min-width: 150px;width: auto;height: auto; padding: 5px;background-color: chartreuse;border-radius: 10px;">
              <el-image :src="item.messageIMG" :z-index="9999" style="width: 150px;height: 120px;"
                :preview-src-list="[item.messageIMG]"></el-image>
            </div>
          </div>
          <div
            v-if="item.userID !== myUser[0].uid && (item.messageIMG !== null && item.messageIMG!=='') && (item.messageSVG === null || item.messageSVG === '') && (item.message === null || item.message ==='')"
            style="width: 100%;height: auto;display: flex;margin-top: 10px;margin-bottom: 10px;">
            <img :src="user.uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
            <div
              style="min-width: 150px;width: auto;height: auto;padding: 5px; background-color: #fff;border-radius: 10px;">
              <el-image :src="item.messageIMG" :z-index="9999" style="width: 150px;height: 120px;"
                :preview-src-list="[item.messageIMG]"></el-image>
            </div>
          </div>
          <div
            v-if="item.userID === myUser[0].uid && (item.messageSVG !== null && item.messageSVG !== '') && (item.messageIMG === null || item.messageIMG ==='') && (item.message === null || item.message ==='')"
            style="width: 100%;height: auto;display: flex;flex-direction: row-reverse;margin-top: 10px;margin-bottom: 10px;">
            <img :src="myUser[0].uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
            <div
              style="min-width: 150px;max-width: 350px;width: auto;height: auto; padding: 5px;background-color: chartreuse;border-radius: 10px;">
              <video ref="video" controls controlslist="nodownload" poster="https://img.chongshe.cn/5164168ff42796c7.jpg" preload="none" width="250" height="200"
                :src="item.messageSVG">
              </video>
            </div>
          </div>
          <div
            v-if="item.userID !== myUser[0].uid && (item.messageSVG !== null && item.messageSVG !== '') && (item.messageIMG === null || item.messageIMG ==='') && (item.message === null || item.message ==='')"
            style="width: 100%;height: auto;display: flex;margin-top: 10px;margin-bottom: 10px;">
            <img :src="user.uphoto" width="60" height="60" style="border: #fff 1px solid;" alt="">
            <div
              style="min-width: 150px;max-width: 350px;width: auto;height: auto;padding: 5px; background-color: #fff;border-radius: 10px;">
              <video ref="video" controls controlslist="nodownload" poster="https://img.chongshe.cn/5164168ff42796c7.jpg" preload="none" width="250" height="200"
                :src="item.messageSVG">
              </video>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div style="width: 720px;position: absolute;bottom: 0px;">
      <div style="display: flex;">
        <el-button :loading="sengIMG" type="primary"
          style="margin: 0 10px 0 0; padding: 0;height: 40px;text-align: center;line-height: 40px;font-size: 16px;">
          <label for="fileImage">
            <p style="width: 117px;height: 40px;line-height: 40px;"><span v-if="!sengIMG">分享图片
                <i class="el-icon-upload el-icon--right"></i></span></p>
          </label>
        </el-button>
        <input v-show="false" type="file" id="fileImage" @change="showImg">

        <el-button :loading="sengSVG" type="primary"
          style="margin: 0 10px 0 0; padding: 0;height: 40px;text-align: center;line-height: 40px;font-size: 16px;">
          <label for="fileVideo">
            <p style="width: 117px;height: 40px;line-height: 40px;"><span v-if="!sengSVG">分享视频<i
                  class="el-icon-upload el-icon--right"></i></span></p>
          </label>
        </el-button>
        <input v-show="false" type="file" id="fileVideo" @change="showVideo">
      </div>
      <div style="display: flex;">
        <el-input type="textarea" :rows="2" v-model="chat" placeholder="请输入内容"
          style="width:650px;font-size: 17px;"></el-input>
        <el-button type="primary" style="width: 80px;height: 50px;font-size: 18px;" @click="roomMessageButton">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import EventBus from '../util/EventBus'
import axios from 'axios'
export default {
  data () {
    return {
      user: [],
      myUser: [JSON.parse(sessionStorage.getItem('user'))],
      messageList: [],
      textarea: '',
      chat: '',
      imgType: 'jpg',
      videoType: 'mp4',
      messageType: '1',
      imgURL: null,
      svgURL: null,
      isShow: false,
      sengIMG: false,
      sengSVG: false
    }
  },
  methods: {
    CreateRoomSeng () {
      if (this.myUser[0].uid != null) {
        axios.defaults.withCredentials = true

        const webSocketUrl = 'ws://152.136.143.223:9091/webSocketSentTo/' + this.myUser[0].uname + '/' + this.myUser[0].uid
        this.webSocketObject = new WebSocket(webSocketUrl)
        this.webSocketObject.onopen = this.webSocketOnOpen
        this.webSocketObject.onmessage = this.webSocketOnMessage
        this.webSocketObject.onerror = this.webSocketOnError
        this.webSocketObject.onclose = this.webSocketOnClose
      }
    },
    webSocketOnOpen (e) {
      console.log('与服务端连接打开->', e)
    },
    webSocketOnMessage (e) {
      const receiveMessage = JSON.parse(e.data)
      this.messageList.push(receiveMessage)
      console.log('->', this.messageList)
    },
    webSocketOnError (e) {
      console.log('与服务端连接异常->', e)
    },
    webSocketOnClose (e) {
      console.log('与服务端连接关闭->', e)
    },
    roomMessageButton () {
      const userID = this.myUser[0].uid
      const sessionID = this.user.uid
      const message = this.chat
      const username = this.myUser[0].uname
      const messageIMG = this.imgURL
      const messageSVG = this.svgURL
      if (messageIMG != null) {
        this.messageType = '2'
      } else if (messageSVG != null) {
        this.messageType = '3'
      }
      const type = this.messageType

      this.chat = ''
      this.messageType = '1'
      this.imgURL = null
      this.svgURL = null

      this.webSocketObject.send(JSON.stringify({
        userID,
        sessionID,
        username,
        type,
        message,
        messageIMG,
        messageSVG,
        time: new Date().getTime()
      }))
    },
    showImg: function (e) {
      const that = this
      this.sengIMG = true
      const file = document.getElementById('fileImage').files[0]
      this.imgType = file.name.substring(file.name.lastIndexOf('.') + 1)
      this.$message({
        showClose: true,
        message: '请等待，图片正在发送'
      })
      if (window.FileReader) {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onloadend = function (e) {
          const data = {
            uphoto: e.target.result.replace(/^data:image\/\w+;base64,/, '')
          }
          axios.defaults.withCredentials = true

          axios({
            url: 'http://152.136.143.223:9091/room/sengIMGANDSVG/' + that.imgType,
            method: 'POST',
            headers: { 'Content-Type': 'application/json;charset=UTF-8' },
            withCredentials: true,
            data: (data)
          }).then((response) => {
            that.sengIMG = false
            that.imgURL = response.data
          })
        }
      }
    },
    showVideo: function (e) {
      this.sengSVG = true
      const that = this
      const file = document.getElementById('fileVideo').files[0]
      this.videoType = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (window.FileReader) {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        this.$message({
          showClose: true,
          message: '请等待，视频正在发送'
        })
        reader.onloadend = function (e) {
          const data = {
            uphoto: e.target.result.replace(/^data:video\/\w+;base64,/, '')
          }

          axios({
            url: 'http://152.136.143.223:9091/room/sengIMGANDSVG/' + that.videoType,
            method: 'POST',
            headers: { 'Content-Type': 'application/json;charset=UTF-8' },
            withCredentials: true,
            data: (data)
          }).then((response) => {
            that.sengSVG = false
            that.svgURL = response.data
          })
        }
      }
    },
    getChatList () {
      axios.defaults.withCredentials = true

      axios({
        url: 'http://152.136.143.223:9091/FriendChat/MsgEx/' + this.myUser[0].uid + '/' + this.user.uid,
        method: 'GET'
      }).then((res) => {
        const div = document.getElementsByClassName('overflow')[0]
        this.messageList = res.data.data
        setTimeout(() => {
          div.scrollTop = div.scrollHeight
        }, 0.1)
        // console.log(this.messageList)
      })
    }
  },
  mounted () {
    EventBus.$on('firend', (user) => {
      this.user = user
      this.isShow = true
    })
  },
  watch: {
    user () {
      this.getChatList()
    },
    imgURL () {
      if (this.imgURL !== null) {
        this.roomMessageButton()
      }
    },
    svgURL () {
      if (this.svgURL !== null) {
        this.roomMessageButton()
      }
    },
    messageList () {
      const div = document.getElementsByClassName('overflow')[0]
      setTimeout(() => {
        div.scrollTop = div.scrollHeight
      }, 0.1)
    }
  },
  created () {
    this.CreateRoomSeng()
  }
}
</script>

<style></style>
